<template>
	<view class="content">
		<view class="" v-if="isIndex">
			<view class="contents">
				<canvas canvas-id="splitCanvas" id="splitCanvas" class="canvas-in"
					:style="{width:canvasInfo.width+'px',height:canvasInfo.height+'px'}"></canvas>
				<view class="image_bg" :style="{width:imgInfo.width+'px',height:imgInfo.height+'px'}">
					<image class="info_image" :src="imgUrl" :style="{width:imgInfo.width+'px',height:imgInfo.height+'px'}">
					</image>
					<view class="move_eare" v-if="imgUrl">
						<view class="mask_bg" :style="{width:imgInfo.width+'px',height:imgInfo.height+'px'}">
							<view class="mask_border"
								:style="{width:selInfo.width+'px',height:selInfo.height+'px',transform:'translate('+(-selInfo.moveX)+'px,'+(-selInfo.moveY)+'px)'}">
								<image class="maskImages" :src="imgUrl"
									:style="{width:imgInfo.width+'px',height:imgInfo.height+'px',transform:'translate('+(selInfo.moveX)+'px,'+(selInfo.moveY)+'px)'}">
								</image>
								<view class="mask_border_cons" :style="{height:selInfo.height+'px'}">
									<view class="border_item" v-for="(item,index) in gridInfo.cutPoint" :key="item.id"
										:style="[{width:selInfo.imgWidth+'px',height:selInfo.imgHeight+'px'},item.borderCons]">
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="tools">
					<view class="cropping" @click="uploadImage">
						上传图片
					</view>
					<view class="cropping" @click="gotoGrid">
						宫格切换
					</view>
					<view class="cropping" @click="gotoScale">
						比例切换
					</view>
					<view class="cropping" @click="croppingImage">
						裁剪图片
					</view>
				</view>
			</view>
			<gird-box :selType="selType" v-if="showTools" :visible.sync="showTools" @select="getGirdData"></gird-box>
		</view>
		<view v-else>
			<result-h5 v-model="isIndex" :datas='clipImgList' :width="selInfo.imgWidth"
				:height="selInfo.imgHeight"></result-h5>
		</view>
	</view>

</template>

<script>
	import {
		scopeAlbum,
		gridData,
		scaleData,
		base64ToFile
	} from '../../utils/common.js'
	import resultH5 from '../components/resultH5/index.vue'
	import girdBox from '../components/girdBox/index.vue'
	let timer = null
	export default {
		components: {
			girdBox,
			resultH5
		},
		data() {
			return {
				imgUrl: 0,
				imgRatio: 0,
				oriImgInfo: {
					width: 0,
					height: 0
				},
				imgInfo: {
					width: 0,
					height: 0
				},
				systemInfo: {
					pixelRatio: 0,
					width: 0,
					height: 0,
					platform: 0,
					dpr: 1
				},
				showTools: false,
				gridInfo: {},
				scaleInfo: {},
				selType: 1,
				selInfo: {
					width: 0,
					height: 0,
					imgWidth: 0,
					imgHeight: 0,
					moveX: 0,
					moveY: 0
				},
				canvasInfo: {
					width: 0,
					height: 0,
					clipWidth: 0,
					clipHeight: 0,
					clipImgWidth: 0,
					clipImgHeight: 0,
					moveX: 0,
					moveY: 0
				},
				clipImgList: [],
				isIndex: true
			}
		},
		onLoad() {
			let info = uni.getSystemInfoSync()
			this.systemInfo.width = info.screenWidth
			this.systemInfo.height = info.screenHeight
			this.systemInfo.pixelRatio = info.pixelRatio
			this.systemInfo.dpr = info.pixelRatio
			this.systemInfo.platform = info.platform
			let data = gridData()[0]
			for (const key in data) {
				this.gridInfo[key] = data[key]
			}
			this.total = this.gridInfo.cutPoint.length
			let data1 = scaleData()[0]
			for (const key in data1) {
				this.scaleInfo[key] = data1[key]
			}
		},
		methods: {
			uploadImage() {
				const that = this
				/*#ifdef MP*/
				return scopeAlbum().then(function(response) {
					that.upImg()
				})
				/*#endif*/
				/*#ifdef APP-PLUS || H5*/
				that.upImg()
				/*#endif*/
			},
			upImg() {
				const that = this
				uni.chooseImage({
					count: 1,
					sizeType: ['original'],
					success: function(res) {
						console.log(res, 'chooseImage--')
						let url = res.tempFilePaths[0]
						that.imageInfo(url)
					},
					fail: function(err) {
						uni.showToast({
							title: '获取图片失败',
							icon: 'none',
							duration: 1500
						})
					}
				})
			},
			imageInfo(url) {
				const that = this
				that.initCanvas()
				uni.getImageInfo({
					src: url,
					success: function(image) {
						that.imgUrl = url
						let imgW = image.width
						let imgH = image.height
						if (that.systemInfo.platform == 'ios') {
							if (imgH / imgW > 2 || imgW / imgH > 3) {
								uni.showModal({
									title: '画布超出比例提示',
									content: '图片宽高比超出2倍，请裁剪后在上传',
									showCancel: false,
									success() {
										uni.reLaunch({
											url: '/pages/index/index',
										})
									}
								})
								return
							}

						} else {
							if (imgH / imgW > 2.6 || imgW / imgH > 3) {
								uni.showModal({
									title: '画布超出比例提示',
									content: '图片宽高比超出2倍，请裁剪后在上传',
									showCancel: false,
									success() {
										uni.reLaunch({
											url: '/pages/index/index',
										})
									}
								})
								return
							}

						}
						const defaultCanvasW = 330
						const scale = defaultCanvasW / imgW
						if (scale < 1) {
							imgW = imgW * scale
							imgH = imgH * scale
						}
						if (that.systemInfo.platform == 'ios') {
							if (imgH / imgW > 1) {
								that.systemInfo.dpr = 2
							} else {
								that.systemInfo.dpr = that.systemInfo.pixelRatio
							}
							if (imgW * that.systemInfo.dpr > 4096 || imgH * that.systemInfo.dpr > 4096) {
								that.systemInfo.dpr = 1.8
							}
						} else {
							that.systemInfo.dpr = that.systemInfo.pixelRatio * 2
							if (imgW * that.systemInfo.dpr > 4096 || imgH * that.systemInfo.dpr > 4096) {
								that.systemInfo.dpr = that.systemInfo.pixelRatio
							}
						}
						console.log(that.systemInfo.dpr, 'that.systemInfo.dpr-----')
						that.oriImgInfo.width = image.width
						that.oriImgInfo.height = image.height
						that.imgInfo.width = imgW
						that.imgInfo.height = imgH
						that.canvasInfo.width = imgW * that.systemInfo.dpr
						that.canvasInfo.height = imgH * that.systemInfo.dpr
						let isCha = (imgW / that.gridInfo.x * that.scaleInfo.wdpr * that.gridInfo.y) - imgH
						that.initSelInfo(isCha, imgW, imgH)

					},
					fail: function(err) {
						uni.showToast({
							title: '获取图片信息失败',
							icon: 'none',
							duration: 1500
						})
					}
				})
			},
			gotoGrid() {
				this.selType = 1
				this.showTools = true
			},
			gotoScale() {
				this.selType = 2
				this.showTools = true
			},
			getGirdData(data) {
				console.log(data, '-=-=', this.selType)
				for (const key in data) {
					if (this.selType == 1) {
						this.gridInfo[key] = data[key]
					} else {
						this.scaleInfo[key] = data[key]
					}
				}
				let isCha = (this.imgInfo.width / this.gridInfo.x * this.scaleInfo.wdpr * this.gridInfo.y) - this.imgInfo.height
				this.initSelInfo(isCha, this.imgInfo.width, this.imgInfo.height)
			},
			initSelInfo(isCha, imgW, imgH) {
				if (this.scaleInfo.id === 0) {
					this.selInfo.width = imgW
					this.selInfo.height = imgH
					this.selInfo.imgWidth = imgW / this.gridInfo.x
					this.selInfo.imgHeight = imgH / this.gridInfo.y
					this.selInfo.moveX = 0
					this.selInfo.moveY = 0
				} else {
					let width = isCha > 0 ? (imgH / this.scaleInfo.h * this.scaleInfo.w / this.gridInfo.y) * this.gridInfo.x : imgW
					let height = isCha > 0 ? imgH : imgW / this.gridInfo.x * this.scaleInfo.wdpr * this.gridInfo.y
					let chaH = imgH - height
					let chaW = imgW - width
					this.selInfo.width = width
					this.selInfo.height = height
					this.selInfo.imgWidth = isCha > 0 ? (imgH / this.scaleInfo.h * this.scaleInfo.w / this.gridInfo.y) : imgW /
						this.gridInfo.x
					this.selInfo.imgHeight = isCha > 0 ? imgH / this.gridInfo.y : imgW / this.gridInfo.x * this.scaleInfo.wdpr
					this.selInfo.moveX = (-chaW / 2)
					this.selInfo.moveY = (-chaH / 2)
				}

			},
			initCanvas() {
				this.ctx = uni.createCanvasContext('splitCanvas', this)
				console.log(this.ctx, '0-0-')
				this.timer = setTimeout(() => {
					this.getDrawImages()
				}, 600)

			},
			getDrawImages() {
				this.ctx.drawImage(this.imgUrl, 0, 0, this.canvasInfo.width, this.canvasInfo.height)
				this.ctx.draw()
				clearTimeout(this.timer)
				this.timer = null
			},
			croppingImage() {
				if (this.imgUrl == '') {
					uni.showToast({
						title: '请上传图片',
						icon: 'none'
					})
					return
				}
				if (!this.ctx) {
					uni.showToast({
						title: '裁剪id丢失，请退出重新进入',
						icon: 'none'
					})
					return
				}
				this.ctx.draw(true, (res) => {
					console.log(res, 'huixhuiii----')
					if (res.errMsg == "drawCanvas:ok") {
						timer = setTimeout(() => {
							uni.showLoading({
								title: '裁剪中...',
								icon: 'none'
							})
							this.cutImage()
						}, 600)
					} else {
						uni.showToast({
							title: '绘制图片加载中...',
							icon: 'none'
						})
					}

				})

			},
			cutImage() {
				clearTimeout(timer)
				timer = null
				let cutx = 0
				let cuty = 0
				let imgUrls = []
				let cutW = this.selInfo.imgWidth * this.systemInfo.dpr
				let cutH = this.selInfo.imgHeight * this.systemInfo.dpr
				let imgW = this.selInfo.imgWidth
				let imgH = this.selInfo.imgHeight
				let cutPoints = this.gridInfo.cutPoint
				let count = 0
				let cfgSave = {
					x: this.selInfo.moveX,
					y: this.selInfo.moveY,
					width: cutW,
					height: cutH,
					destWidth: cutW * this.systemInfo.dpr,
					destHeight: cutH * this.systemInfo.dpr,
					canvasId: 'splitCanvas'
				}
				let cutNum = this.gridInfo.cutNum
				let that = this
				let cutFlag = true
				timer = setInterval(() => {
					console.log(timer, 'timer---', cutFlag)
					if (cutFlag) {
						cutFlag = false
						cutx = cutPoints[count].x
						cuty = cutPoints[count].y
						cfgSave.x = cutW * cutx + (-this.selInfo.moveX) * this.systemInfo.dpr
						cfgSave.y = cutH * cuty + (-this.selInfo.moveY) * this.systemInfo.dpr
						console.log(cutPoints, 'cutPoints===')
						uni.canvasToTempFilePath({
							...cfgSave,
							success: function(res) {

								let url = res.tempFilePath
								/*#ifdef H5*/
								// url = base64ToFile(url) 

								/*#endif*/
								console.log(url, '裁剪中---')
								cutFlag = true
								count++
								uni.showLoading({
									title: `裁剪中 ${count}/${cutNum}`,
									mask: true
								})
								let data = {
									id: count,
									path: url
								}
								imgUrls.push(data)
								console.log(imgUrls, 'imgUrls---')
								if (count == cutNum) {
									if (imgUrls.length < cutNum) {
										imgUrls = []
										return
									}
									clearInterval(timer)
									timer = null
									uni.hideLoading()
									timer = setTimeout(() => {
										/*#ifndef H5*/
										let list = JSON.stringify(imgUrls)
										let path = '/pages/result/index?data=' + list + '&width=' + imgW + '&height=' + imgH
										uni.redirectTo({
											url: path
										})
										/*#endif*/
										/*#ifdef H5*/
										that.clipImgList = imgUrls
										that.isIndex = false
										/*#endif*/

										clearTimeout(timer)
										timer = null
									}, 500)
								}
							},
							fail: function(err) {
								clearInterval(timer)
								timer = null
								uni.showModal({
									title: '温馨提示',
									content: '剪切图片失败',
									showCancel: false,
									success() {
										cutFlag = true
										uni.reLaunch({
											url: '/pages/index/index'
										})
									}
								})
								console.log(err, '剪切失败')
							}
						})
					}

				}, 1000)

			},
		}
	}
</script>

<style>
	.content {
		width: 100vw;
		min-height: 100vh;
		background-color: #0E0E12;
		padding-top: 0;
		padding-bottom: 200rpx;
		box-sizing: border-box;
		position: relative;
		overflow: hidden;

	}

	.contents {
		width: 660rpx;
		margin: 0 auto;
		min-height: calc(100vh - 160rpx);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.image_bg {
		width: 100%;
		height: 100%;

		position: relative;
	}

	.info_image {
		display: block;
	}

	.move_eare {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 39;
		box-sizing: border-box;
	}

	.tools {
		width: 100vw;
		height: 160rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 26rpx;
		padding-bottom: 100rpx;
		box-sizing: border-box;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 9999999;
	}

	.cropping {
		width: 150rpx;
		height: 78rpx;
		background: #0E5AD3;
		border-radius: 16rpx;
		font-size: 26rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: bold;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		line-height: 37rpx;
	}

	.mask_bg {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 28;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.mask_border {
		position: relative;
		z-index: 9999;
		overflow: hidden;

	}

	.maskImages {
		display: block;
		position: relative;
	}

	.mask_border_cons {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 99999;
		display: flex;
		flex-wrap: wrap;
		box-sizing: border-box;
	}

	.border_item {
		flex-shrink: 0;
		border: 2px solid #FFFFFF;
		box-sizing: border-box;
	}

	.canvas-in {
		margin: 0 auto;
		position: absolute;
		left: -999999px;
		top: -999999px;
		z-index: 0;
	}
</style>